package actions

import (
	"QWenVL/utils"
	"context"
	"errors"
	"net/http"
	"runtime/debug"

	"github.com/sagikazarmark/slog-shim"
)

type HumaOut[T any] struct {
	Status int
	Body   Response[T]
}

type Response[T any] struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data *T     `json:"data"`
}

func humaAdaptor[R any, T any](action func(ctx context.Context, input *T) (*R, error)) func(ctx context.Context, input *T) (*HumaOut[R], error) {
	return func(ctx context.Context, input *T) (*HumaOut[R], error) {
		resp, err := action(ctx, input)
		if !utils.IsNil(err) {
			var msgError *utils.MsgError
			if errors.As(err, &msgError) {
				slog.Error("MsgError", "err", msgError.Error())
				return &HumaOut[R]{
					Status: msgError.HttpStatus,
					Body: Response[R]{
						Code: msgError.Code,
						Msg:  msgError.Message,
					},
				}, nil
			}

			slog.Error("unknown internal error message", "err", err)
			debug.PrintStack()
			return &HumaOut[R]{
				Status: http.StatusInternalServerError,
				Body: Response[R]{
					Code: 5001000,
					Msg:  "unknown internal error message",
				},
			}, nil
		}

		return &HumaOut[R]{
			Status: http.StatusOK,
			Body: Response[R]{
				Code: 0,
				Data: resp,
				Msg:  "",
			},
		}, nil
	}
}
